package comp6231.project.replica.dimitri;
/**
 * Distributed Retail System
 * Oct 3, 2012 
 */


import java.net.*;
import java.util.Hashtable;
import java.io.*;

/**
 * @author dimitri.tiago
 *
 * This class implements a UDP/IP retail stock server that
 * returns the number of items in the stock for a particular
 * item.
 */
public class UDPRetailStockServer implements Runnable
{
	private RetailStoreStock stock; 	// retail store stock reference 
	private int port; 			// server port to listen for requests
	
	private static Hashtable<Integer, DatagramSocket> sockets;
	
	public UDPRetailStockServer(int port, RetailStoreStock stock)
	{
		this.port  = port;
		this.stock = stock;
		sockets = new Hashtable<Integer, DatagramSocket>();
	}

	@Override
	public void run()
	{
		DatagramSocket aSocket = null;

		try
		{
			if (getSocket(port) == null)
			{
				aSocket = new DatagramSocket(port);
				sockets.put(port, aSocket);
			}
			else
			{
				aSocket = getSocket(port);
			}

			while(true)
			{
				byte[] buffer 	       = new byte[1000];
				DatagramPacket request = new DatagramPacket(buffer, buffer.length);
				aSocket.receive(request); // listen for request on socket

				// process request in new thread
				UDPRetailStockServerProcessorThread udpProcessorThread = new UDPRetailStockServerProcessorThread(aSocket, request, stock);
				Thread processorThread = new Thread(udpProcessorThread);
				processorThread.start();
			}
		}
		catch (SocketException e)
		{
			System.out.println("Socket: " + e.getMessage());
		}
		catch (IOException e) 
		{
			System.out.println("IO: " + e.getMessage());
		}
		finally 
		{
			if(aSocket != null) 
			{
				aSocket.close();
			}
		}
	}
	
	public DatagramSocket getSocket(int port)
	{
		return sockets.get(port);
	}
}	